#include "mainwindow.h"

#include <QGridLayout>
#include <QTreeWidgetItem>
#include <QMap>
#include <QMouseEvent>
#include <QMimeData>

#include <QMenu>
#include <QMenuBar>

#include <QInputDialog>

#include <QtDebug>
#include <QNetworkReply>
#include <QStandardItemModel>
#include <qheaderview.h>
#include <QVBoxLayout>
#include <QLabel>

using namespace Playur;

ListViewWidget::ListViewWidget()
    : drag(0)
{

}

MainWindow::MainWindow()
{
  searchModel = NULL;
    QMenu* fileMenu = menuBar()->addMenu("File");
    fileMenu->addAction("Add Library...", this, SLOT(openAddLibraryDialog()));
    
    QWidget* centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    
    QLineEdit* searchField;
    QHBoxLayout* searchZone = new QHBoxLayout;
    searchZone->addWidget(new QLabel(tr("Search:")));
    searchZone->addWidget(searchField = new QLineEdit);
    connect(searchField, SIGNAL(textChanged(QString)), this, SLOT(applySearch(QString)));
    
    QVBoxLayout* layout = new QVBoxLayout;
    layout->addLayout(searchZone);
    layout->addWidget(&tableWidget);
    
    centralWidget->setLayout(layout);
    
    model = new CollectionItemModel;
    tableWidget.setModel(model->getListProxy());

    connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(readReply(QNetworkReply*)));
}

void MainWindow::addCollection(const QString& xml)
{
    model->addCollection(xml);
}

void MainWindow::readReply(QNetworkReply* reply)
{
    QString data = reply->readAll();
    QString address;
    if(reply->url().host() == "127.0.0.1")
      address = QString("http://") + reply->url().host() + ":" + QString::number(reply->url().port());
    model->addCollection(data, address);
}

void MainWindow::fetchCollection(QString ip)
{
  networkAccessManager.get(QNetworkRequest(QUrl(QString("http://") + ip + "/list")));
}

void ListViewWidget::mousePressEvent(QMouseEvent* event)
{
    QTableView::mousePressEvent(event);

    qDebug() << "mousepressevent";

    QVariant item = ((QStandardItemModel*)model())->data(currentIndex(), Qt::UserRole);
    TrackInfo* track = static_cast<TrackInfo*>(item.value<void*>());
    if(!track) return;

    QMimeData* mimeData = new QMimeData;
    mimeData->setText(track->urlBase.append(QString::number(track->id, 10)));

    drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->exec(Qt::CopyAction, Qt::CopyAction);
}

void ListViewWidget::mouseReleaseEvent(QMouseEvent* event)
{
  QTableView::mouseReleaseEvent(event);
}

void ListViewWidget::leaveEvent(QEvent *event)
{
  QTableView::leaveEvent(event);
}

void MainWindow::openAddLibraryDialog()
{
    fetchCollection(QInputDialog::getText(this, "Ajouter un serveur", "IP du serveur"));
}

void MainWindow::applySearch(const QString& search)
{  
}

